<template>
  <view class="address-container">
    <!-- 地址列表 -->
    <view class="address-list" v-if="addressList.length > 0">
      <view class="address-item" v-for="(item, index) in addressList" :key="index">
        <view class="info-section" @click="handleAddressClick(item)">
          <view class="user-info">
            <text class="name">{{item.receiverName}}</text>
            <text class="phone">{{item.phoneNumber}}</text>
            <text class="tag" v-if="item.isDefault">默认</text>
          </view>
          <view class="address-detail">
            <text>{{item.provinceName || ''}} {{item.cityName || ''}} {{item.districtName || ''}} {{item.detailedAddress || ''}}</text>
          </view>
        </view>
        <view class="action-section">
          <view class="action-btn" @click="handleEdit(item)">
            <text class="icon">✎</text>
            <text>编辑</text>
          </view>
          <view class="action-btn" @click="handleDelete(item)">
            <text class="icon">🗑</text>
            <text>删除</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <text>暂无收货地址</text>
    </view>
    
    <!-- 底部按钮 -->
    <view class="footer">
      <button class="add-btn" @click="addAddress">新增收货地址</button>
    </view>
  </view>
</template>

<script>
import { userApi, systemApi } from '@/api'
export default {
  data() {
    return {
      addressList: [],
      isSelectMode: false, // 是否是选择地址模式
      loading: false,
      eventChannel: null,
      orderData: null, // 存储订单数据
      from: '' // 来源标记
    }
  },
  
  onLoad(options) {
    // 判断是否是选择地址模式
    this.isSelectMode = options.select === 'true' || options.from === 'buy'
    this.from = options.from || ''
    
    // 如果是从商品详情页来的，获取订单数据
    if (options.from === 'buy' && options.orderData) {
      this.orderData = JSON.parse(decodeURIComponent(options.orderData))
    }
    
    this.loadAddressList()
    
    // 获取事件通道
    if (this.isSelectMode) {
      const eventChannel = this.getOpenerEventChannel()
      this.eventChannel = eventChannel
    }
  },
  onShow() {
    this.loadAddressList() // 每次显示页面时加载最新数据
  },
  // 下拉刷新
  async onPullDownRefresh() {
    await this.loadAddressList()
    uni.stopPullDownRefresh()
  },
  // 监听返回按钮点击
  onNavigationBarButtonTap(e) {
    if (e.type === 'back') {
      uni.navigateBack()
    }
  },
  methods: {
    // 加载地址列表
    async loadAddressList() {
      try {
        this.loading = true
        const data  = await userApi.getAddress()
        this.addressList = data || []
      } catch (error) {
        console.error('获取地址列表失败:', error)
        uni.showToast({
          title: '获取地址列表失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 点击地址项
    async handleAddressClick(address) {
      if (this.from === 'buy') {
        // 如果是从商品详情页来的，直接创建订单
        try {
          uni.showLoading({
            title: '提交订单中...'
          })
          
          // 合并地址ID到订单数据
          const orderParams = {
            ...this.orderData,
            addressId: address.id
          }
          
          // 调用直接下单接口
          await userApi.createDirectOrder(orderParams)
          
          uni.hideLoading()
          uni.showToast({
            title: '下单成功',
            icon: 'success'
          })

          // 跳转到订单列表页
          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/order/list/index'
            })
          }, 1500)
        } catch (error) {
          uni.hideLoading()
          console.error('创建订单失败:', error)
          uni.showToast({
            title: error.message || '创建订单失败',
            icon: 'none'
          })
        }
      } else if (this.isSelectMode) {
        // 通过事件通道返回选中的地址
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.emit('addressSelected', address)
        uni.navigateBack()
      } else {
        // 普通模式，跳转到编辑页面
        uni.navigateTo({
          url: `/pages/address/edit/index?id=${address.id}`
        })
      }
    },
    
    async handleDelete(address) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该地址吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await userApi.deleteAddress(address.id)
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })
              // 重新加载地址列表
              this.loadAddressList()
            } catch (error) {
              console.error('删除地址失败:', error)
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    handleEdit(address) {
      uni.navigateTo({
        url: `/pages/address/edit/index?id=${address.id}`
      })
    },
    
    addAddress() {
      uni.navigateTo({
        url: '/pages/address/edit/index'
      })
    }
  }
}
</script>

<style>
.address-container {
  min-height: 100vh;
  background: #f8f8f8;
  padding-bottom: 120rpx;
}

.address-list {
  padding: 20rpx;
}

.address-item {
  background: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.info-section {
  padding-bottom: 20rpx;
}

.user-info {
  margin-bottom: 16rpx;
}

.name {
  font-size: 32rpx;
  font-weight: 500;
  margin-right: 20rpx;
}

.phone {
  font-size: 28rpx;
  color: #666;
}

.tag {
  font-size: 20rpx;
  color: #ff4d4f;
  border: 1rpx solid #ff4d4f;
  padding: 2rpx 12rpx;
  border-radius: 16rpx;
  margin-left: 16rpx;
}

.address-detail {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
}

.action-section {
  display: flex;
  justify-content: flex-end;
  padding-top: 20rpx;
  border-top: 1rpx solid #eee;
}

.action-btn {
  display: flex;
  align-items: center;
  margin-left: 40rpx;
  font-size: 28rpx;
  color: #666;
}

.action-btn .icon {
  font-size: 32rpx;
  margin-right: 8rpx;
}

.empty-state {
  padding-top: 200rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}

.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.add-btn {
  background: var(--primary-color);
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
  height: 88rpx;
  line-height: 88rpx;
}

.add-btn:active {
  opacity: 0.9;
}
</style> 